#include "stdio.h"
#include "stdlib.h"
#include "sys/types.h"
#include "sys/mman.h"
#include "sys/stat.h"
#include "unistd.h"
#include "pthread.h"
#include "signal.h"
#include "string.h"
#include "fcntl.h"



int main()
{
	char *shm = "sharemem";
	char *shm1 = "sharemem1";

	int shm_id, shm1_id;
	char *buf;
	pid_t pid;

	pthread_mutex_t *mutex;
	pthread_mutexattr_t mutex_attr;

	shm_id = shm_open(shm, O_RDWR | O_CREAT, 0644);
	ftruncate(shm_id, 100);
	buf = (char *)mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);

	shm1_id = shm_open(shm1, O_RDWR | O_CREAT, 0644);
	ftruncate(shm1_id, 100);
	mutex = (pthread_mutex_t *)mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_SHARED, shm1_id, 0);

	pthread_mutexattr_init(&mutex_attr);

#ifdef _POSIX_THREAD_PROCESS_SHARED
	pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_PRIVATE);
	//pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
#endif

	pthread_mutex_init(mutex, &mutex_attr);

	pid = fork();

	if(!pid){
		sleep(1);
		printf("child process 0x%x\n", getpid());

		pthread_mutex_lock(mutex);
		memcpy(buf, "hello", 6);
		printf("child buf is %s\n", buf);
		pthread_mutex_unlock(mutex);
	}else if(pid > 0){
		printf("parent process 0x%x, my child is 0x%x\n", getpid(), pid);

		pthread_mutex_lock(mutex);
		memcpy(buf, "world", 6);
		sleep(3);
		printf("parent buf is %s\n", buf);
		pthread_mutex_unlock(mutex);
	}

	pthread_mutexattr_destroy(&mutex_attr);
	pthread_mutex_destroy(mutex);

	munmap(buf, 100);
	munmap(mutex, 100);

	shm_unlink(shm);
	shm_unlink(shm1);

	return 0;
}
